package cloud.shyidong.admin.system.service;

import cloud.shyidong.core.request.LongIdRequest;
import cloud.shyidong.core.service.AbstractService;
import cloud.shyidong.core.util.ObjectUtils;
import cloud.shyidong.system.dao.SystemMenuDao;
import cloud.shyidong.system.entity.SystemMenuEntity;
import cloud.shyidong.system.request.SystemMenuInsertRequest;
import cloud.shyidong.system.request.SystemMenuPageRequest;
import cloud.shyidong.system.request.SystemMenuUpdateRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表业务处理
 * </p>
 *
 * @author syd
 * @since 2023-05-31 13:14:46
 */
@Service
public class SystemMenuService extends AbstractService<SystemMenuDao, SystemMenuEntity, LongIdRequest, SystemMenuInsertRequest, SystemMenuUpdateRequest, SystemMenuPageRequest> {
    
    @Override
    public Map<String, Object> view(LongIdRequest idRequest) {
        Map<String, Object> result = super.view(idRequest);
        if (result.containsKey("parentId")) {
            Long parentId = (Long) result.get("parentId");
            if (ObjectUtils.isNotNull(parentId) && parentId > 0) {
                SystemMenuEntity systemMenuEntity = getDao().selectById(parentId);
                result.put("parentName", systemMenuEntity.getName());
            }
        }
        return result;
    }
    
    @Override
    public List<SystemMenuEntity> search(SystemMenuPageRequest pageRequest) {
        List<SystemMenuEntity> result = new ArrayList<>();
        List<SystemMenuEntity> systemMenuEntities = super.search(pageRequest);
        Map<Long, SystemMenuEntity> systemMenuMap = systemMenuEntities.stream().collect(Collectors.toMap(SystemMenuEntity::getId, systemMenuEntity -> systemMenuEntity));
        for (SystemMenuEntity systemMenuEntity : systemMenuEntities) {
            if (ObjectUtils.isNull(systemMenuEntity.getParentId())) {
                result.add(systemMenuEntity);
            } else {
                SystemMenuEntity parentMenuEntity = systemMenuMap.get(systemMenuEntity.getParentId());
                if (ObjectUtils.isNull(parentMenuEntity)) {
                    result.add(systemMenuEntity);
                } else {
                    parentMenuEntity.getTreeList().add(systemMenuEntity);
                }
            }
        }
        return result;
    }
    
}
